Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

File Handling in java → Write file

File Handling in java

Write file

Writing Files in Java

Java provides several methods to write data to text files. The choice of method depends on factors like the type of data you're writing (characters, formatted strings), desired efficiency, and control over formatting. Here are three common methods:

1. Using FileWriter and BufferedWriter:

FileWriter: This class creates a stream for writing characters to a text file. BufferedWriter: This class wraps around a FileWriter and provides buffering capabilities for improved performance, especially when writing large amounts of data.
Write using bufferedWriter try { // Create a FileWriter object for the desired file path (can use true for append mode) FileWriter writer = new FileWriter("data.txt"); // Create a BufferedWriter for efficiency BufferedWriter bufferedWriter = new BufferedWriter(writer); // Write data to the file bufferedWriter.write("This is some data to write.\n"); bufferedWriter.write("This is another line to append.\n"); bufferedWriter.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); // Handle potential exceptions }
Explanation: FileWriter writer = new FileWriter("data.txt", true);: This line creates a FileWriter object associated with the file path "data.txt". The true argument (optional) enables appending data to an existing file. BufferedWriter bufferedWriter = new BufferedWriter(writer);: This line creates a BufferedWriter object that wraps around the FileWriter for buffering. bufferedWriter.write("...");: This method writes the specified string data to the file. You can call write() multiple times to write different content. bufferedWriter.close() and writer.close(): These lines close the writer objects, releasing resources and ensuring all data is flushed to the file.

2. Using PrintWriter Class:

PrintWriter: This class is a higher-level writer that inherits from BufferedWriter and offers methods for formatted output similar to System.out.print(). It can handle primitive data types (like int, double) and strings.
Writing to file using PrintWriter try { PrintWriter writer = new PrintWriter(new File("data.txt")); writer.println("This is some formatted data:"); writer.printf("Integer value: %d, Double value: %.2f\n", 10, 3.14); writer.close(); } catch (IOException e) { e.printStackTrace(); // Handle potential exceptions }
Explanation: PrintWriter writer = new PrintWriter(new File("data.txt"));: This line creates a PrintWriter object associated with the file "data.txt". writer.println("...");: This method writes a line of text followed by a newline character (\n) to the file. writer.printf("...", arguments);: This method provides formatted output similar to System.out.printf(), allowing you to insert values into strings. writer.close(): This line closes the writer object, releasing resources.

3. Using Files.write() (Java 7 and above):

Files Class (Java 7+): This class provides static methods for various file operations. Here, we'll use Files.write(). write(): This method writes all bytes of a byte array to a file. It's suitable for writing binary data or strings encoded as bytes. Here's an example (assuming the data is already a byte array):
Writing to file using write() method try { byte[] data = "This is some data to write.".getBytes(); Files.write(Paths.get("data.txt"), data); } catch (IOException e) { e.printStackTrace(); // Handle potential exceptions }
Explanation: byte[] data = ...: This line prepares the data as a byte array (ensure proper encoding for strings). Files.write(Paths.get("data.txt"), data);: This line writes the entire byte array data to the file "data.txt". Choosing the Right Approach: FileWriter and BufferedWriter: This combination is ideal for efficient character-by-character or line-by-line writing of text files. PrintWriter: Use PrintWriter for formatted output similar to console printing, allowing you to write both strings and formatted primitive data types. Files.write(): This method is suitable for writing binary data or byte arrays to files.

Tutorials